package com.cloud.product.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cloud.product.dao.ProductCategoryDao;
import com.cloud.product.dao.ProductInfoDao;
import com.cloud.product.dto.CartDTO;
import com.cloud.product.pojo.ProductCategory;
import com.cloud.product.pojo.ProductInfo;
import com.cloud.product.service.ProductService;
import com.cloud.product.vo.ProductInfoVO;
import com.cloud.product.vo.ProductVo;
import com.cloud.product.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/product")
public class ProductInfoController {

    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private ProductCategoryDao productCategoryDao;
    @Autowired
    private ProductService productService;

    /**
     * 1  查询所有在架的商品
     * 2  查询类目的type表
     * 3  查询类目
     * 4  构造数据
     */
    @GetMapping(value = "/list",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO<List<ProductVo>> list() {
        List<ProductCategory> categories = productCategoryDao.selectList(null);
        List<ProductVo> data = categories.stream().map(this::getProductVO).collect(Collectors.toList());
        return ResultVO.createBySuccess(data);
    }

    private ProductVo getProductVO(ProductCategory productCategory) {
        return  ProductVo.builder().categoryName(productCategory.getCategoryName())
                .categoryType(productCategory.getCategoryType())
                .productInfoVOList(
                productInfoDao.selectList(Wrappers.<ProductInfo>lambdaQuery()
                        .eq(ProductInfo::getCategoryType, productCategory.getCategoryType()))
                        .stream().map(this::getProductInfoVO).collect(Collectors.toList())
                ).build();
    }

    private ProductInfoVO getProductInfoVO(ProductInfo productInfo) {
        ProductInfoVO productInfoVO = new ProductInfoVO();
        BeanUtils.copyProperties(productInfo, productInfoVO);
        return productInfoVO;
    }


    @PostMapping("/listForOrder")
    public List<ProductInfo> listForOrder(@RequestBody List<String> productIdList) {
        List<ProductInfo> productInfos = productInfoDao.selectList(Wrappers.<ProductInfo>lambdaQuery().in(ProductInfo::getProductId, productIdList));
        return productInfos;
    }

    @PostMapping("/decreaseStock")
    public void decreaseStock(@RequestBody List<CartDTO> cartDTOS) {
        productService.decreaseStock(cartDTOS);
    }

}
